package com.wlyuan.index.domain.index.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;

import java.util.Map;

/**
 * @author yuanjie
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ExtractUtils {

    public static void fill(Map<String, Object> values, Aggregation agg) {
        if (agg instanceof ParsedSum) {
            ParsedSum sum = (ParsedSum) agg;
            values.put(sum.getName(), sum.getValue());
        } else if (agg instanceof ParsedCardinality) {
            ParsedCardinality cardinality = (ParsedCardinality) agg;
            values.put(cardinality.getName(), cardinality.getValue());
        } else if (agg instanceof ParsedValueCount) {
            ParsedValueCount count = (ParsedValueCount) agg;
            values.put(count.getName(), count.getValue());
        } else if (agg instanceof ParsedNested) {
            ParsedNested nested = (ParsedNested) agg;
            nested.getAggregations().forEach(sub -> fill(values, sub));
        }
    }

    public static void fill(Map<String, Object> values, Aggregations aggs) {
        aggs.forEach(agg -> fill(values, agg));
    }
}
